//
//  SHIdentityViewController.m
//  JiFengDaRen
//
//  Created by SH_iOS on 2018/1/9.
//  Copyright © 2018年 SH_iOS. All rights reserved.
//
//高级人脸实名认证
#import "HBRSAHandler.h"
#import <IdentitySDK/DetectViewController.h>
#import <IdentitySDK/LMSTakePhotoController.h>
#import <identitySDK/identitySDK.h>

#import "SHCreditCardTfCell.h"
#import "SHCreditFooterCell.h"
#import "SHIdentityViewController.h"

@interface SHIdentityViewController ()<UITableViewDelegate,UITableViewDataSource,SHCreditFooterCellDelegate,LMSTakePhotoControllerDelegate,SHCreditCardTfCellDelegate>
{
    NSString *name;//需要认证的名字
    NSString *idNo;//需要认证的身份证id
    NSString *appId;//appId
    NSString *appKey;//appKey
    
    DetectViewController *identity;
    LMSTakePhotoController *takepic;
    NSString * _orderNo;//请求获取订单号
    NSInteger _type;//认证模式（7：信息认证，8实人认证）
    UITextField *nametxt;
    UITextField *idtxt;
}

//姓名
@property(nonatomic,strong)SHCreditCardTfCell *nameCell;
//身份证号码
@property(nonatomic,strong)SHCreditCardTfCell *cerCardNocell;
@property(nonatomic,strong)SHCreditFooterCell *footerCell;


@property(nonatomic,strong)UITableView *identityInfoTable;
@property(nonatomic,assign)BOOL isClickedBtn;
@property(nonatomic,strong)NSString *clickedBtnTitle;


@end

static AFHTTPSessionManager *manager;

@implementation SHIdentityViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"实名认证";
    _isClickedBtn = YES;
    _clickedBtnTitle = @"点击拍摄身份证";
    [self identityInfoTable];
    
}


#pragma mark - 卡片管理列表
- (UITableView *)identityInfoTable{
    
    if (!_identityInfoTable) {
        
        _identityInfoTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight - KSAFEHEIGHT - KNAVIGATIONBARHEIGHT ) style:UITableViewStyleGrouped];
        _identityInfoTable.delegate = self;
        _identityInfoTable.dataSource = self;
        _identityInfoTable.backgroundColor = KBASEBGCOLOR;
        _identityInfoTable.estimatedSectionHeaderHeight = 0;
        _identityInfoTable.estimatedSectionFooterHeight = 0;
        //        _creditCardInfoTable.sectionHeaderHeight = __I6Height(11);
        //        _creditCardInfoTable.sectionFooterHeight = 0.01;
        
        [self.view addSubview:_identityInfoTable];
        _identityInfoTable.separatorStyle =  UITableViewCellSeparatorStyleNone;
        
    }
    return _identityInfoTable;
}


#pragma mark --- UITablView  & DataSource  & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    if (section == 0) {
        
        return 2;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
  
     return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        
        return  __I6Height(122);

    }else{
        
        return __I6Height(45);
        
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {//
        if(indexPath.row == 0){
            _nameCell = [tableView dequeueReusableCellWithIdentifier:@"identitynameCell"];
            if (!_nameCell) {
                _nameCell = [[SHCreditCardTfCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"identitynameCell"];
                _nameCell.placeholder = @"请如实填写";
                _nameCell.labelText = @"*真实姓名";
//                _nameCell.contentTf.enabled = NO;
                _nameCell.line.hidden = NO;
                _nameCell.delegate = self;
            }
            _nameCell.line.hidden = NO;
            
            return _nameCell;
        }else{
            _cerCardNocell = [tableView dequeueReusableCellWithIdentifier:@"identitycerCardNocell"];
            if (!_cerCardNocell) {
                _cerCardNocell = [[SHCreditCardTfCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"identitycerCardNocell"];
                _cerCardNocell.placeholder = @"请输入身份证号码";
                _cerCardNocell.labelText = @"*证件号码";
//                _cerCardNocell.contentTf.enabled = NO;
                _cerCardNocell.delegate = self;

            }
            
            _cerCardNocell.line.hidden = YES;
            
            return _cerCardNocell;
        }
        
    
        
    }else{
        
        
        _footerCell = [tableView dequeueReusableCellWithIdentifier:@"footerCell"];
        if (!_footerCell) {
            _footerCell = [[SHCreditFooterCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            _footerCell.delegate = self;
            
        }
        _footerCell.buttonTitle  = _clickedBtnTitle;
        _footerCell.isClickedBtn = _isClickedBtn;
//     [_footerCell.changeBtn setBackgroundImage:[UIImage imageWithColor:KREDCOLOR size:CGSizeMake(__I6Width(326), __I6Height(42))] forState:UIControlStateNormal];
        return _footerCell;
    }
    
}


#pragma mark SHCreditCardTfCellDelegate
- (BOOL)creditCardTfCellTextField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
                replacementString:(NSString *)string{
    
    return YES;
}


#pragma mark - SHCreditFooterCellDelegate
- (void)changeFooter:(SHCreditFooterCell *)footer changeCardBtn:(UIButton *)sender{
    
    [self.view endEditing:YES];
//    if([_nameCell.contentTf.text length] == 0 ){
//
//        [self.view makeToast:@"请输入真实姓名" duration:2.f position:@"center"];
//
//        return;
//
//    }
//    if([_cerCardNocell.contentTf.text length] == 0 ){
//
//        [self.view makeToast:@"请输入身份证号码" duration:2.f position:@"center"];
//
//        return;
//    }
   
    
   [self isTakePicAction];//拍照识别身份证号码 姓名
    
}





#pragma mark - 人脸实名认证下单接口 签名
- (NSDictionary *)createSignWithDictionary:(NSDictionary *)params appKey:(NSString *)appKey{
    
    
    NSArray *allKeyArray = [params allKeys];
    
 
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSComparisonResult resuest = [[obj1 lowercaseString] compare:[obj2 lowercaseString]];
        return resuest ;//
    }];
    SHLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [params objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    SHLog(@"valueArray:%@",valueArray);
    
    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0 ; i < afterSortKeyArray.count; i++) {
        
        NSString *keyValue = [NSString stringWithFormat:@"%@=%@",afterSortKeyArray[i],valueArray[i]];
        [signArray addObject:keyValue];
    }
    
    //signString用于签名的原始参数集合
    NSString *keyString = [signArray componentsJoinedByString:@"&"];
    NSString *signString = [NSString stringWithFormat:@"%@&key=%@",keyString,appKey];
    NSLog(@"signString:%@",signString);
    NSMutableDictionary *body = [[NSMutableDictionary alloc]initWithDictionary:params];
    [body setValue:[signString MD5] forKey:@"sign"];
    
    return  body;
}

//第一次请求获取认证订单号
- (void)goFirstRequest{
    
    appId = @"xUszTSOjFAQOjcuQ";//appId
    appKey = @"JfEQmkrTYKrtMkFCNXCZWDPAJaxWVNux";//appKey

    if([name length] == 0 && [idNo length] == 0){
        
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入认证名字和身份证号!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
        return;
    }
    
    identity = [[DetectViewController alloc]init];
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *certFilePath = [[NSBundle mainBundle] pathForResource:@"identity" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:certFilePath];
//    AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//    policy.allowInvalidCertificates = YES;
//    policy.validatesDomainName = NO;
    //    [policy setPinnedCertificates:[NSSet setWithArray:@[certData]]];
//    [policy setPinnedCertificates:@[certData]];
    manager = [AFHTTPSessionManager manager];
//    manager.securityPolicy = policy;
    //关闭缓存避免干扰测试  psb_auth/api/v1/id_auth
    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    //    NSString * url = @"http://runkapay.com/identification/preIdentify";//获取认证订单号链接
    NSString *url = @"http://api.mychinavvv.com/psb_auth/api/v1/id_auth";
    //    NSString *url =  @"http://192.168.31.199:80/api/api/identification/preIdentify";
    //    NSString *url =  @"http://fzfx.gnway.org:21302/identification";
    name = [name stringByReplacingOccurrencesOfString:@" " withString:@""];
    idNo = [idNo stringByReplacingOccurrencesOfString:@" " withString:@""];
//    NSString *signString =
//    [NSString stringWithFormat:@"appId=%@&idNo=%@&name=%@&key=%@",appId,idNo,name,appKey];
//    NSLog(@"signString:%@",signString);
   

    NSDictionary * paramet =
    @{
      @"name":name,
      @"idNo":idNo,
      @"appId":appId ,
//      @"sign":[signString md5]
      };
    SHLog(@"paramet:%@",paramet);
  //签名
   NSDictionary *signBody = [self createSignWithDictionary:paramet appKey:appKey];
    [manager POST:url parameters:signBody progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        SHLog(@"%@",responseObject);
        
        if ([responseObject[@"success"] boolValue]) {
            _orderNo = responseObject[@"data"][@"orderNo"];
            NSLog(@"_orderNo:%@",_orderNo);//订单号
            if(_type == 7){
                
                [self goToSecond];
                
            }else{
                
                [self livingDetectAction];
            }
            
        }else{
            
            [identity.view removeFromSuperview];
            [self.view makeToast:responseObject[@"data"] duration:2.f position:@"center"];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"firstRequest——error：%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [identity.view removeFromSuperview];
        
        [self.view makeToast:@"拼命链接中，稍等哈" duration:2.f position:@"center"];

        
    }];
   
   
}

#pragma mark - 拍照识别姓名 卡号
- (void)isTakePicAction{
    
  
    takepic = [[LMSTakePhotoController alloc] init];
    if (!takepic.isAuthorizedCamera || !takepic.isCameraAvailable) {
        SHLog(@"不能拍照");
        return;
    }
    //注释以下两行其中一行可以实现身份证正面照拍摄或者背面照拍摄
    takepic.functionType = TakePhotoIDCardFrontType;
    //    p.functionType = TakePhotoIDCardBackType;
    takepic.delegate = self;
    [self presentViewController:takepic animated:YES completion:NULL];
}

#pragma LMSTakePhotoControllerDelegate
- (void)didFinishPickingImg:(id)getName idNo:(id)getIdNo
{
    

    name = getName;
    idNo = getIdNo;
    _nameCell.contentTf.text = name;
    _cerCardNocell.contentTf.text = idNo;
    [self.identityInfoTable reloadData];
    [takepic dismissViewControllerAnimated:YES completion:nil];

    _type = 8;
    
//    if (![_nameCell.contentTf.text isEqualToString:name]) {
//        
//        [self.view makeToast:@"填写的姓名与拍照识别的姓名不一致" duration:2.f position:@"center"];
//        return;
//    }
//    
//    if (![_cerCardNocell.contentTf.text isEqualToString:idNo]) {
//        
//        [self.view makeToast:@"填写的身份证号码与拍照识别的身份证号码不一致" duration:2.f position:@"center"];
//        return;
//    }
    [self goFirstRequest];
}

- (void)livingDetectAction{
    
    if([[NSString stringWithFormat:@"%ld",(long)_type] isEqualToString:@"8"]){
        
        [[UIApplication sharedApplication].keyWindow addSubview:identity.view];
        [identity setDetect:@"1"];
        __weak typeof(self) weakSelf = self;
        identity.takepicBlock = ^(UIImage *image){
            
            [weakSelf goToSecond];
        };
        
    }else{
        
        [self goToSecond];
    }
}

- (void)goToSecond{
    
    //name:姓名 idnum:身份证号 type:识别类型 （7：信息认证，8实人认证） inputorderNo：订单号
    [self goidentiyaction:[NSString stringWithFormat:@"%ld",(long)_type] inputorderNo:_orderNo];
}

//执行二次认证
- (void)goidentiyaction:(NSString *)_gettype inputorderNo:(NSString *)_inputorderNo{
     @weakify(self)
    [identity type:_gettype inputorderNo:_inputorderNo];
    identity.resultBlock = ^(NSDictionary *result){
        @strongify(self)
        //认证返回结果
        SHLog(@"result:%@",result);
        //1,认证成功。0.认证失败
        NSString *message;
        switch ([result[@"result"] intValue]) {
            case 0:
            {
                message = @"认证失败";

            
            }
                return ;
            case 1:
            {
                message = @"认证成功";

                [self postUserIdentityInfoName:name idNumber:idNo identiyimg:result[@"img"] fullImg:result[@"fullImg"]];

            }
                
                return ;
            case 2:
                message = @"连接超时或者连接失败";
                break;
            default:
                break;
        }
        //        UIImage *identiyimg = result[@"img"];//认证图片
        //        UIImage *fullImg = result[@"fullImg"];//全景图片
//        [weakSelf.view makeToast:message duration:2.f position:@"center"];
    
    };
    
}





/**
 上传人脸识别认证结果

 @param name 姓名
 @param idNumber 身份证号
 @param identiyimg  认证图片
 @param fullImg 全景图片
 */
- (void)postUserIdentityInfoName:(NSString *)name
                        idNumber:(NSString *)idNumber
                      identiyimg:(UIImage *)identiyimg
                         fullImg:(UIImage *)fullImg{
    
    
    [SHQiniuManager qiniuUploadImage:identiyimg complete:^(NSString *qnImageUrl) {
        [SHHomeModelView psbAuthName:name idNo:idNumber authImg:qnImageUrl Success:^(BOOL suceesss) {
            _isClickedBtn = NO;
            _clickedBtnTitle = @"认证成功";
            [self.identityInfoTable reloadData];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5  * NSEC_PER_SEC));
            
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });

        }];
        
    }];
}

   
    

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
